<template>
  <div class="app-container">
    <div class="title">{{ id !== ':id' ? '编辑' : '创建' }}积分规则</div>
    <div class="formbox">
      <el-form ref="ruleForm" label-position="left" label-width="80px" :model="formLabelAlign" :rules="rules" >
        <el-form-item label="分类名称" prop="category_name">
          <el-select v-model="formLabelAlign.category_id" placeholder="请选择垃圾类型" style="width: 100%">
            <el-option v-for="item in categories" :key="item.id" :label="item.category_name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="分类类型" prop="integral_base">
          <el-input v-model="formLabelAlign.integral_base" placeholder="请输入分值"/>
        </el-form-item>
        <el-form-item align="center">
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button v-if="id === ':id'" @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Integral',
  data() {
    return {
      categories: [],
      formLabelAlign: {},
      rules: {
        category_id: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        integral_base: [
          { required: true, message: '请输入分值', trigger: 'blur' }
        ]
      },
      id: null
    }
  },
  created() {
    this.id = this.$route.params.id
  },
  mounted() {
    this.id !== ':id' && this.getById(this.id)
    this.getCategories()
  },
  methods: {
    async getCategories() {
      const res = await this.$http.get('/cms/category/list')
      this.categories = res.data.rows
    },
    async getById(id) {
      const res = await this.$http.get(`/cms/integral/findOne/${id}`)
      if (res.code === 0) {
        const { category_id, integral_base } = res.data
        this.formLabelAlign = { category_id, integral_base }
      }
    },
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate(async valid => {
        if (valid) {
          if (this.id !== ':id') {
            const res = await this.$http.put(`/cms/integral/update/${this.id}`, { ...this.formLabelAlign })
            if (res.code === 0) {
              this.$message({
                message: res.message,
                type: 'success',
                duration: 2000
              })
              // this.$router.push('/integral/index')
            }
          } else {
            const res = await this.$http.post('/cms/integral/create', { ...this.formLabelAlign })
            if (res.code === 0) {
              this.$message({
                message: res.message,
                type: 'success',
                duration: 2000
              })
              this.formLabelAlign = {}
            }
          }
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
